export default {
  translate2Rows(roots) {
    const entryArray = Array.isArray(roots) ? roots : [roots]
    const {deep} = this.calcLevelLeaf(entryArray)
    let result = []
    entryArray.forEach(i => {
      result.push(this.getRows(i, deep))
    })

    if (result.length === 1) {
      return result[0]
    }
    return result
  },
  getNodeById(data, id) {
    if (data.id === id) {
      return data
    }
    let children = data.children || []
    for (var i = 0, len = children.length; i < len; i++) {
      let res = this.getNodeById(children[i], id)
      if (res) {
        return res
      }
    }
    return null
  },
  getParentByChildId(data, id, parent) {
    if (data.id === id) {
      return parent
    }
    let children = data.children || []
    for (let i = 0; i < children.length; i++) {
      let result = this.getParentByChildId(children[i], id, data)
      if (result) {
        return result
      }
    }
    return null
  },
  hasChildren(item) {
    return this._hasChildren(item)
  },
  _hasChildren(item) {
    if (item && item.children && item.children.length) {
      return true
    } else {
      return false
    }
  },
  getRows(data, deep) {
    //先序遍历到尽头
    let stack = []
    let RowsResult = []
    let result = []
    stack.push(data)
    while (stack.length) {
      let top = stack.pop()
      // 保存到结果集内
      let item = {
        ...top,
        children: null,
        rowSpan: top.leafCount
      }
      if (this._hasChildren(top)) {
        item.colSpan = 1
        //非叶子节点
      } else {
        item.colSpan = deep - top.level + 1
      }
      result.push(item)
      let children = top.children
      if (children && children.length > 0) {
        for (let i = children.length - 1; i >= 0; i--) {
          stack.push(children[i])
        }
      } else {
        //叶子节点，划分割线，新数组开始
        RowsResult.push(result)
        result = []
      }
    }
    return RowsResult
  },
  /**
   * 递归建立以下内容：
   * 树的每个节点的深度（根节点深度为1）;
   * 每个节点下属所有的叶子（包括孙子和所有后代）个数;
   * 节点是否是leaf
   *
   * @param {*} arr
   * @param {*} parentLevel
   * 返回，有效内容为当前节点的所有后代叶子个数，所有后代节点中，最深的节点的深度
   */
  calcLevelLeaf(arr, parentLevel = 0) {
    let count = 0
    let deep = parentLevel + 1
    arr.forEach(item => {
      item.level = parentLevel + 1
      item.leafCount = 0
      if (this._hasChildren(item)) {
        const {count: c, deep: d} = this.calcLevelLeaf(
          item.children,
          item.level
        )
        item.leafCount += c
        item.isLeaf = false
        count += c
        deep = Math.max(deep, d)
      } else {
        item.isLeaf = true
        item.leafCount = 1
        count += 1
      }
    })
    return {
      count,
      deep
    }
  }
}
